<script setup lang="ts">
import { ref, watch } from 'vue';
import { UploadProps, UploadUserFile } from 'element-plus';
const imageUrl = ref<string | undefined>(undefined)
const fileList = ref<UploadUserFile[]>([])
const inFile = ref()
interface Props {
  isDisabled?: boolean,
  Url?: string
}
const props = defineProps<Props>()

// 监视Url属性变化，当Url被清空时，重置组件状态
watch(() => props.Url, (newVal) => {
  if (!newVal) {
    imageUrl.value = undefined;
    fileList.value = [];
    inFile.value = undefined;
  }
})

const handleFileChange: UploadProps["onChange"] = (uploadFile) => {
  // 清除fileList并重置，确保上传组件状态正确
  fileList.value = [uploadFile];
  // 更新本地图片URL
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  inFile.value = uploadFile.raw;
  // 触发confirm事件
  confirm();
}
const emit = defineEmits(["confirm"])
const confirm = () => {
  emit("confirm", inFile.value)
}
const handleFileExceed: UploadProps["onExceed"] = (files) => {

}

</script>

<template>
  <div>
    <el-upload ref="UploadFileRef" class="avatar-uploader" :disabled="isDisabled" v-model:file-list="fileList" :limit="1"
      :show-file-list="false" accept="image/png,image/jpeg,image/gif" :auto-upload="false" :on-exceed="handleFileExceed"
      :on-change="handleFileChange">
      <img v-if="Url" :src="Url.startsWith('blob:') ? Url : `/model-api${Url}`" class="avatar" />
      <img v-else-if="imageUrl" :src="imageUrl" class="avatar" />
      <div v-else class="avatar-uploader-icon">
        <el-icon>
          <Plus />
        </el-icon>
        <span class="describe">点击上传缩略图</span>
      </div>
    </el-upload>
  </div>
</template>
<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #409EFF;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background-color: #ECF5FF;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20px;
  width: 178px;
  height: 178px;

  .el-icon {
    font-size: 28px;
    color: #8c939d;
  }

  .describe {
    color: #409EFF;
  }
}
</style>
